from django.shortcuts import render

# Create your views here.

from rest_framework.views import APIView
from rest_framework.response import Response
from .serializer import *
from django.core.paginator import Paginator


class RegisterView(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        password2 = request.data.get('password2')
        if UserModel02.objects.filter(username=username):
            return Response({'msg': '该用户已存在'})
        if password2 == password:
            ser = UserSer(data=request.data)
            if ser.is_valid():
                ser.save()
                return Response({'msg': '注册成功', 'code': 200})
            else:
                return Response({'errors': ser.errors})
        else:
            return Response({'msg': '两次密码不一致', 'code': 400})


class LoginView(APIView):
    def post(self, request):
        password = request.data.get('password')
        username = request.data.get('username')
        user_obj = UserModel02.objects.filter(username=username).first()
        if user_obj:
            if password == user_obj.password:
                return Response({'msg': '登录成功', 'code': 200, 'qx': user_obj.qx, 'user_id': user_obj.id})
            else:
                return Response({'msg': '用户或密码不正确', 'code': 400})
        else:
            return Response({'msg': '用户或密码不正确', 'code': 400})


class CourseView(APIView):  # 课程的添加，展示，删除
    def post(self, request):
        course_name = request.data.get('course_name')
        if CourseModel.objects.filter(course_name=course_name):
            return Response({'msg': '该课程已存在', 'code': 400})
        ser = CourseSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({'msg': '添加成功', 'code': 200})
        else:
            return Response({'errors': ser.errors})

    def get(self, request):
        current_page = request.query_params.get('current_page')  # 当前页
        course_obj = CourseModel.objects.order_by('course_number').all()  # 获取课程所有数据
        paginotor = Paginator(course_obj, 3)  # 每页展示三条
        paged = paginotor.page(current_page)  # 获取当前页
        ser = CourseSer(paged, many=True)
        return Response({
            'data': ser.data,  # 当前页数据
            'page_list': [i for i in paginotor.page_range],  # 页码列表
            'page_sum': paginotor.num_pages  # 总页数
        })

    def delete(self, request):
        course_id = request.data.get('course_id')
        course_obj = CourseModel.objects.filter(pk=course_id).first()
        if course_obj:
            course_obj.delete()
            return Response({'msg': '删除成功', 'code': 200})
        else:
            return Response({'msg': '删除失败', 'code': 400})
